import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:simple_app/common/api.dart';
import 'package:simple_app/common/global.dart';
import 'package:simple_app/common/storage_util.dart';
import 'package:simple_app/tab_list.dart';

import 'main.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final user = TextEditingController();
  final pwd = TextEditingController();

  @override
  void initState() {
    super.initState();

    //login页面进入，判断token不为空，如果不为空跳转到tablist页
    if (Platform.isAndroid) {
      Api().getToken().then((token) {
        if (token != '') {
          StorageUtil.getString('id').then((id) {
            StorageUtil.getString('user').then((user) {
              StorageUtil.getString('pwd').then((pwd) {
                StorageUtil.getString('nickname').then((nickname) {
                  loginIn(token, id, nickname, user, pwd);
                  MyApp.navKey.currentState?.popAndPushNamed('/index',
                      arguments: TabListRouteArgs(name: nickname));
                });
              });
            });
          });
        }
      });
    }
  }

  Widget textbox(String text, TextEditingController controller) {
    var txt = '请输入$text';
    return TextFormField(
      controller: controller,
      decoration: InputDecoration(
          focusedBorder: InputBorder.none,
          enabledBorder: InputBorder.none,
          errorBorder: InputBorder.none,
          disabledBorder: InputBorder.none,
          // hintStyle: const TextStyle(color: Color.fromARGB(255, 255, 255, 255)),
          hintText: txt),
      validator: (String? value) {
        if (value == null || value.isEmpty) {
          return '请填写$text';
        }
        return null;
      },
    );
  }

  var issubmit = false;

  //登录所需要缓存的信息
  loginIn(String token, String id, String nickname, String user, String pwd) {
    //记录token
    Api().setToken(token);

    //记录一些信息
    StorageUtil.putString('nickname', nickname);
    StorageUtil.putString('user', user);
    StorageUtil.putString('pwd', pwd);
    StorageUtil.putString('id', id);

    Global.webSocketClient(user, pwd);
    Api.userInfo = UserInfo(id: id, name: nickname);
  }

  Container logbtn(BuildContext ctx) {
    return Container(
      padding: const EdgeInsets.fromLTRB(0, 15, 0, 0),
      child: ElevatedButton(
          style: ButtonStyle(
              padding: MaterialStateProperty.all(
                  const EdgeInsets.fromLTRB(0, 15, 0, 15))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const [
              Text('登 录'),
            ],
          ),
          onPressed: () {
            if (_formKey.currentState!.validate()) {
              if (issubmit) {
                return;
              }
              issubmit = true;

              Api().login(user.text, pwd.text).then((response) {
                if (response == null) {
                  ScaffoldMessenger.of(ctx).showSnackBar(
                    const SnackBar(content: Text('服务器错误')),
                  );
                  issubmit = false;
                  return;
                }
                if (response.statusCode != 200) {
                  ScaffoldMessenger.of(ctx).showSnackBar(
                    const SnackBar(content: Text('服务器错误')),
                  );
                  issubmit = false;
                  return;
                }
                var data = jsonDecode(response.body);
                if (data['status'] != 1) {
                  ScaffoldMessenger.of(ctx).showSnackBar(
                    SnackBar(content: Text(data['info'])),
                  );
                } else {
                  //登录成功

                  loginIn(data['token'], data['id'], data['nickname'],
                      user.text, pwd.text);

                  Navigator.popAndPushNamed(context, '/index',
                      arguments: TabListRouteArgs(name: data['nickname']));
                  // Navigator.push(ctx,
                  //     MaterialPageRoute(builder: (context) => const TabList()));
                }
                issubmit = false;
              });
              // var txt = '请求中... ${user.text} ${pwd.text}';
              // ScaffoldMessenger.of(context).showSnackBar(
              //   SnackBar(content: Text(txt)),
              // );

              //jump

            }
          }),
    );
  }

  GestureDetector regbtn(BuildContext ctx) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(ctx, '/reg');
      },
      child: const Text(
        '注 册',
        style: TextStyle(color: Color(0xffff0000)),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 0,
      ),
      body: Container(
        alignment: Alignment.topCenter,
        child: Container(
            // height: 200,
            decoration: const BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(5)),
                color: Color.fromARGB(255, 255, 255, 255)),
            margin: const EdgeInsets.fromLTRB(60, 100, 60, 0),
            padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
            child: Form(
                key: _formKey,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    textbox('用户名', user),
                    textbox('密码', pwd),
                    logbtn(context),
                    regbtn(context),
                  ],
                ))),
      ),
    );
  }
}
